<template>
    <div class="orderConfirm">
        <!-- 顶部导航栏 -->
        <div class="header">
            <van-sticky>
                <van-nav-bar title="订单确认" left-text="返回" left-arrow @click-left="$router.go(-1)" />
            </van-sticky>
        </div>
        <!-- 服务地址区域 -->
        <div class="address" @click="showAddress">
            <div>
                <!-- 服务地址 -->
                <div style="color: #323233;">
                    <van-icon name="location-o" size="16" /><span style="margin-left: 5px;">服务地址</span>
                </div>
                <!-- 姓名 电话 -->
                <div style="color:#969799;font-size: 14px;">
                    <span style="margin-right: 10px;">姓名：{{selectAddress.name}}</span>
                    <span>电话：{{selectAddress.tel}}</span>
                    <!-- 地址 -->
                    <div><span>地址：{{selectAddress.address}}</span></div>
                </div>
            </div>
        </div>
        <!-- 订单详情区域 -->
        <div class="orderDetail">
            <div>
                <div style="color: #323233;">
                    <van-icon name="orders-o" size="16" /><span style="margin-left: 5px;">订单详情</span>
                    <!-- 服务项目 价格 数量 -->
                    <div style="color:#969799;font-size: 14px;" class="detailProject">
                        <van-row v-for="line of orderLines.values()" :key="line.productId">
                            <div style="display: flex;justify-content: space-between;">
                                <span>{{line.productName}}</span>
                                <span>￥{{line.price}}</span>
                                <span>x{{line.number}}</span>
                            </div>
                        </van-row>

                        <!-- 分割线-->
                        <van-divider />
                        <div style="display: flex;justify-content: space-between;">
                            <span>总价：</span><span>￥{{total}}</span></div>
                    </div>
                </div>
            </div>
        </div>
        <!-- 服务时间区域 -->
        <div class="serviceTime" @click="showTime=true">
            <div>
                <div style="color: #323233;">
                    <div style="display: flex;justify-content: space-between;">
                        <div>
                            <van-icon name="aim" size="12" />
                            <span style="margin-left: 5px;">服务时间</span>
                        </div>
                        <div><span style="color: #969799;font-size: 14px;">{{currentDate}}</span></div>
                    </div>

                </div>
            </div>
        </div>
        <!-- 确认提交按钮 -->
        <div class="submit">
            <div class="submitBtn" @click="showPasswordInput">确认提交</div>
        </div>

        <!-- 地址面板 -->
        <van-action-sheet v-model="show" title="选择地址">
            <div class="content">
                <van-address-list v-model="chosenAddressId" @click-item="select" :list="addressList"
                    add-button-text="确定" @add="onConfirm" default-tag-text="默认" @edit="onEdit" />
            </div>
        </van-action-sheet>

        <!-- 修改地址动作面板 -->
        <van-action-sheet v-model="editAddress" title="修改地址">
            <van-form @submit="onSubmitEditForm" ref="form">
                <van-field v-model="editFormNow.name" name="username" label="姓名" placeholder="姓名"
                    :rules="[{ required: true, message: '请填写姓名' }]" />
                <van-field v-model="editFormNow.tel" name="telephone" label="电话" placeholder="电话"
                    :rules="[{ required: true, message: '请填写电话' }]" />

                <van-field readonly clickable name="area" :value="addressStr" label="地区选择" placeholder="点击选择省市区"
                    @click="showArea = true" />
                <van-popup v-model="showArea" position="bottom">
                    <van-area :area-list="areaList" @confirm="onConfirmAddress" @cancel="onCancel" />
                </van-popup>
                <van-field v-model="addressDetail" name="address" label="详细地址" placeholder="详细地址"
                    :rules="[{ required: true, message: '请填写详细地址' }]" />
                <div style="margin: 16px;">
                    <van-button round block type="info" native-type="submit">提交</van-button>
                </div>
            </van-form>
        </van-action-sheet>


        <!-- 服务时间面板 -->
        <van-action-sheet v-model="showTime" title="选择服务时间">
            <van-datetime-picker v-model="currentDate" type="datetime" title="" :min-date="minDate" :max-date="maxDate"
                :formatter="formatter" @confirm="Change" @cancel="showTime=false" @change="Change" />
        </van-action-sheet>
        <!-- 密码输入框弹出层 -->
        <van-popup v-model="showPop" :style="{ width:'90%', height: '50%' }">
            <!-- 密码输入框 -->
            <van-password-input :value="value" :focused="showKeyboard" @focus="showKeyboard = true" info="密码为 6 位数字"
                :error-info="errorInfo" />
            <van-number-keyboard v-model="value" :show="showKeyboard" @blur="showKeyboard = false" />
        </van-popup>
        <div style="height: 80px;"></div>
    </div>
</template>
<script>
    import {
        areaList
    } from '@vant/area-data';
    // 引入vuex的辅助函数
    import {
        mapActions,
        mapState,
        mapGetters,
        mapMutations
    } from 'vuex'
    import {
        get,
        post,
        post_json
    } from '@/http/axios'
    export default {
        data() {
            return {
                show: false,
                chosenAddressId: 0,
                // 地址数据
                addressList: [],
                // 选中的地址
                selectAddress: {},
                showTime: false,
                currentDate: new Date(),
                minDate: new Date(),
                maxDate: new Date(2021, 12, 1),
                // 时间戳
                timestamp: '',
                // 解析出来的对象
                line: [],
                // 提交订单成功对象
                message: '',
                // 数字键盘的值
                value: '',
                showKeyboard: true,
                showPop: false,
                errorInfo: '',
                editAddress: false,
                // 提交修改表单
                eidtSubForm: {
                    // 省
                    province: "",
                    // 市
                    city: "",
                    // 区
                    area: "",
                    // 具体地址
                    address: "",
                    // 收货人姓名
                    username: "",
                    // 收货人电话
                    telephone: "",
                    // 地址id
                    id: "",
                    userId: "",
                },
                // 当前修改地址
                editFormNow: {

                },
                addressStr: '',
                showArea: false,
                areaList, // 数据格式见 Area 组件文档,
                // 根据地址分割
                province: '',
                city: '',
                area: '',
                // 具体地址
                addressDetail: '',
                // 地址点击修改Id
                formId: ''



            }
        },
        created() {
            this.getAllAddress()
            this.queryUser()
            this.Change()
            // 将时间转换成时间戳
            this.changeTimeToChuo()
            // 解析orderLines
            this.orderLineChange()
        },
        computed: {
            ...mapState('user', ['userInfo']),
            ...mapState('shopcart', ['orderLines']),
            // 购物车总价
            ...mapGetters('shopcart', ['total']),
        },
        watch: {
            value(value) {
                if (value.length === 6 && value !== this.userInfo.password) {
                    this.errorInfo = '密码错误';
                } else if (value.length === 6 && value == this.userInfo.password) {
                    this.errorInfo = '';
                    // 密码正确支付
                    this.submitOrder()
                }
            },
        },
        methods: {
            ...mapActions('user', ['getUserInfo']),
            ...mapMutations('shopcart', ['addShopcart', 'clearShopcart']),
            // 解析obejectMap对象即orderLine
            orderLineChange() {
                for (let line of this.orderLines.values()) {
                    this.line.push(line)
                }
            },
            //取消选中城市
            onCancel() {
                this.showArea = false;
                //this.$refs.myArea.reset(); // 重置城市列表
            },
            //确定选择城市
            onConfirm(values) {
                this.show = false;
            },
            // 提交订单显示支付密码框
            showPasswordInput() {
                this.$dialog.alert({
                    title: '支付金额',
                    message: '￥' + this.total,
                    theme: 'round-button',
                }).then(async () => {
                    // 展示密码输入框
                    this.showPop = true;
                });

            },
            // 提交订单接口
            async submitOrder() {
                let changeLine = [...this.line]
                delete changeLine[0].productName
                changeLine[0].id = 0
                changeLine[0].orderId = 0
                let order = {
                    addressId: this.chosenAddressId,
                    customerId: this.userInfo.id,
                    orderLines: changeLine,
                    serviceTime: this.timestamp
                }
                let res = await post_json('/order/submitOrder', order)
                if (res.status == 200) {
                    this.showPop = false
                    this.$toast.success("支付成功!");
                    this.$router.push({
                        path: '/manager/order'
                    })
                }
            },
            // 将时间转换成时间戳
            changeTimeToChuo() {
                var date = new Date(this.currentDate)
                this.timestamp = date.getTime()
                // this.timestamp = this.timestamp / 1000;
            },
            // 将时间选择器的值转换成默认值
            Change() {
                this.showTime = false
                var date = this.currentDate;
                var seperator1 = "-";
                var seperator2 = ":";
                var month = date.getMonth() + 1;
                var strDate = date.getDate();
                var hour = date.getHours();
                var minute = date.getMinutes() > 9 ? date.getMinutes() : "0" + date.getMinutes();
                if (month >= 1 && month <= 9) {
                    month = "0" + month;
                }
                if (strDate >= 0 && strDate <= 9) {
                    strDate = "0" + strDate;
                }
                if (hour >= 0 && hour <= 9) {
                    hour = "0" + hour;
                }
                this.currentDate =
                    date.getFullYear() +
                    seperator1 +
                    month +
                    seperator1 +
                    strDate +
                    " " +
                    hour +
                    seperator2 +
                    minute +
                    seperator2 +
                    "00";
            },

            formatter(type, val) {
                if (type === 'year') {
                    return val + '年';
                }
                if (type === 'month') {
                    return val + '月';
                }
                if (type === 'day') {
                    return val + '日';
                }
                if (type === 'hour') {
                    return val + '时';
                }
                if (type === 'minute') {
                    return val + '分';
                }
                return val;
            },
            select(item) {
                this.selectAddress = item
            },
            // 确定
            onConfirmAddress(val) {
                this.addressStr = val
                    .filter((item) => !!item)
                    .map((item) => item.name)
                    .join("-");

                this.province = val[0].name;
                this.city = val[1].name;
                this.area = val[2].name;
                this.showArea = false //关闭弹框
            },
            // 编辑地址
            onEdit(item, index) {
                this.formId = item.id
                this.editFormNow = item
                // 根据地址分割
                var index11 = 0;
                var index1 = this.editFormNow.address.indexOf('省');
                var index3 = 0;
                if (index1 == -1) {
                    index11 = this.editFormNow.address.indexOf('自治区');
                    if (index11 != -1) {
                        this.province = this.editFormNow.address.slice(0, index11 + 3)
                    } else {
                        this.province = this.editFormNow.address.slice(0, 3)
                        index3 = 1
                    }
                } else {
                    this.province = this.editFormNow.address.slice(0, index1 + 1)
                }
                var index2 = this.editFormNow.address.indexOf("市")
                if (index3 == 1) {
                    this.city = this.editFormNow.address.slice(0, 3); //没有市就取到省
                    index2 = 5
                } else {
                    if (index11 == 0) {
                        this.city = this.editFormNow.address.slice(index1 + 1, index2 + 1); //有值从省取到市
                    } else {
                        this.city = this.editFormNow.address.slice(index11 + 3, index2 + 1); //从自治区取到市
                    }
                }

                var newAddress = item.address.slice(index2 + 1)


                var index3 = newAddress.indexOf("区")
                if (index3 == -1) {
                    index3 = newAddress.indexOf("县");
                    this.area = newAddress.slice(0, index3 + 1)
                } else {
                    this.area = newAddress.slice(0, index3 + 1)
                    this.addressDetail = newAddress.slice(index3 + 1)
                }

                // 展示面板
                this.editAddress = true
                // 显示级联选择地址
                this.addressStr =
                    this.province + "-" + this.city + "-" + this.area;
            },

            onSubmitEditForm(values) {
                this.eidtSubForm.id = this.formId
                this.eidtSubForm.userId = this.userInfo.id;
                this.eidtSubForm.username = values.username
                this.eidtSubForm.telephone = values.telephone
                this.eidtSubForm.province = this.province
                this.eidtSubForm.area = this.area
                this.eidtSubForm.city = this.city
                this.eidtSubForm.address = values.address
                this.$refs.form
                    .validate()
                    .then(async () => {
                        let res = await post("/address/saveOrUpdate", this.eidtSubForm);
                        this.addressList = []
                        this.getAllAddress();
                        this.$toast.success("修改成功");
                    })
                    .catch(() => {
                        this.$toast.fail("修改失败");
                    });
                this.editAddress = false

            },
            // 分页查询获取地址栏数据
            async getAllAddress() {
                let data = {
                    page: 1,
                    pageSize: 100,
                    userId: this.userInfo.id
                }
                let res = await get('/address/pageQuery', data);

                let addressArr = res.data.data.list;
                if (!addressArr) {
                    return;
                }
                addressArr.forEach((item, index) => {
                    let addressObj = {}
                    addressObj.id = item.id,
                        addressObj.name = item.username,
                        addressObj.tel = item.telephone,

                        // 显示详细地址
                        this.detailAddress = item.address;
                    // 拼接地址
                    addressObj.address = item.province + item.city + item.area + item.address
                    if (addressObj.id == 2300) {
                        addressObj.isDefault = true
                    } else {
                        addressObj.isDefault = item.isDefault
                    }
                    this.addressList.push(addressObj)
                    // 默认选中的id
                    this.chosenAddressId = this.addressList[0].id
                    // 赋值默认进来的地址
                    this.selectAddress = this.addressList[0]

                });
            },
            // 获取用户信息
            queryUser() {
                this.getUserInfo()
            },
            // 点击切换地址
            showAddress() {
                // 显示地址面板
                this.show = true
            }
        },
    }
</script>
<style scoped>
    .submitBtn {
        width: 53%;
        height: 40px;
        background-image: linear-gradient(-20deg, #ddd6f3 0%, #faaca8 100%, #faaca8 100%);
        text-align: center;
        color: #fff;
        border-radius: 22px;
        line-height: 40px;
        margin: 0 auto;
        margin-top: 2em;
        cursor: pointer;
    }

    /* 提交按钮 */
    .submit {
        margin: 0 auto;
    }

    .van-divider {
        margin: 8px 0;
    }

    .address,
    .orderDetail,
    .serviceTime {
        width: 100%;
        box-shadow: 2px 2px 2px 2px rgb(158 117 255 / 20%);
        border-radius: 5px;
        transition: .3s;
        height: 100px;
        padding: 20px;
        box-sizing: border-box;
        margin-top: 10px;
    }

    .orderDetail {
        height: 120px;
        margin-top: 10px;
    }

    .orderConfirm {
        width: 95%;
        margin: 0 auto;
    }

    .serviceTime {
        height: 48px;
    }
</style>